package com.zhome.gateway.filter.pre;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.enums.FilterEnum;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.filter.AbstractZhomeZuulFilter;
import com.zhome.gateway.locator.MySqlClientRouteLocator;
import com.zhome.gateway.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * 验证Token，也就是接口需要登录访问
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class BlackListFilter extends AbstractZhomeZuulFilter {

    @Autowired
    private MySqlClientRouteLocator mySqlClientRouteLocator;

    @Override
    public String filterType() {
        return Constants.PRE_KEY;
    }

    @Override
    public int filterOrder() {
        return FilterEnum.TokenValidateFilterEnum.getFilterOrder();
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String ip = RequestUtil.getRemoteIP(request);
        String ua = request.getHeader(Constants.RequestHeader.USER_AGENT);
        String token = request.getHeader(Constants.RequestHeader.TOKEN);
        if (mySqlClientRouteLocator.isBlackIp(ip)
            || mySqlClientRouteLocator.isBlackUa(ua)
            || mySqlClientRouteLocator.isBlackToken(token)) {
            setSkipToPostTypeFilter(ctx);
            setFailResponse(GateWayCodeEnum.BLACK_IP_FAIL);
        }
        return null;
    }

}
